'''
This script calculates the percentage/count of the occurrence of each label in the training file
and stores that information in a map file : stats.map => key: line_number value: most_frequent_label 
'''

import pickle
import sys

#every label is refered to an integer number throughout the program and for later references
class Labels:
    POPULATION = 0
    INTERVENTION = 1
    BACKGROUND = 2
    OUTCOME = 3
    STUDY_DESIGN = 4
    OTHERS = 5
    
def resetCounters():
    global counts
    counts = [0 for i in range(6)]

def calcPercentage(noOfLines,currentLine):
    global counts
    global map
    labels = Labels()
    label_name_list = ["population","intervention","background","outcome","study design","other"]
    
    #percents = []
    #for i in range(len(counts)):
    #    percents.append(str(float(counts[i] * 100) / float(noOfLines)))
           
    max_count = max(float(counts[labels.POPULATION]),float(counts[labels.INTERVENTION]),float(counts[labels.BACKGROUND]),
                      float(counts[labels.OUTCOME]),float(counts[labels.STUDY_DESIGN]),float(counts[labels.OTHERS]))

    #print str(maxi)
    for i in range(len(label_name_list)):
        if(max_count == float(counts[i])):
            map[currentLine] = label_name_list[i]
            #print map[currentLine]
            break


num_of_parameters = len(sys.argv)
if (num_of_parameters > 1 or num_of_parameters < 1):
    print "usage: python calculate_stats.py"
    sys.exit(0)

counts = []
counts = [0 for i in range(6)]
map_file = open("stats.map","w")
labels_map = { 'population':0, 'intervention':1,'background':2,'outcome':3, 'study design':4, 'other':5 }
map = {}

#for each line-number create a mapping to it's most frequent label
overal_line_counter = 0
line_counter = 0
fin = open("new_train.csv","r")
while True:
    l = fin.readline()
    if not l:
        break
    overal_line_counter += 1
    if l == "\n":
        line_counter += 1
        calcPercentage(overal_line_counter,line_counter)
        resetCounters()
    else:
        counts[ labels_map[l.strip()] ] += 1
        
#store the statistic in a map to a file for later reference
pickle.dump(map, map_file)
